package ddd.ajava.chapter2.question6;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;

import ddd.ajava.util.StringUtil;

/**
 * @author lenovo
 * 提取接口步骤如下
 * 1.获取包名
 * 2.获取类名，合成接口名
 * 3.反射获取方法名，进行比较
 * 4.相同方法名的提取为接口
 */
public class ExtInterface {
	private static final String BLANK=" ";
	private static final String TAB="\t";
	private StringBuilder sb=new StringBuilder();
	private Class personClass=Person.class;
	private Class teacherClass=Teacher.class;
	
	public static void main(String[] args) {
		ExtInterface ext=new ExtInterface();
		ext.getPackageDesc();
		String interfaceName=ext.getInterfaceDesc();
		ext.extract();
		ext.generateOutput(interfaceName);
	}
	
	private void getPackageDesc(){
		String packageDesc=personClass.getPackage().getName();
		sb.append("package "+packageDesc+";\n");
	}
	
	private String getInterfaceDesc(){
		String pName=personClass.getSimpleName();
		String tName=teacherClass.getSimpleName();
		String interfaceName=pName+tName;
		sb.append("\n"+"public interface "+interfaceName+"{");
		return interfaceName;
	}
	
	private void extract(){
		Method[] pMethods=personClass.getDeclaredMethods();
		Method[] tMethods=teacherClass.getDeclaredMethods();
		for(Method p:pMethods){
			String pMethodName=p.getName();
			for(Method t:tMethods){
				String tMethodName=t.getName();
				if(pMethodName.equals(tMethodName)){
					//方法名相同，提取为接口方法
					Class[] param=p.getParameterTypes();
					//有参数的方法，要在类型后面添加变量名
					if(param.length>0){
						StringBuilder paramSB=new StringBuilder();
						paramSB.append(p.getName()+"(");
						String arg="arg";
						for(int i=0;i<param.length;i++){
							paramSB.append(param[i].getCanonicalName()+BLANK+arg+i+",");
						}
						paramSB=new StringBuilder(paramSB.substring(0, paramSB.length()-1));
						paramSB.append(");");
						String name=p.toString();
						name=name.replaceFirst("\\S(\\w*\\.*)*\\((\\w*\\.*\\ *)*\\)",paramSB.toString());
						sb.append("\n"+TAB+name+"\n");
						continue;
					}
					
					String name=p.toString();
					name=name.replaceFirst("\\S(\\w*\\.*)*\\(",p.getName()+"(");
					sb.append("\n"+TAB+name+";\n");
					break;
				}
			}
		}
		sb.append("\n"+"}");
	}
	
	private void generateOutput(String interfaceName) {
		String path = personClass.getPackage().getName().replace(".", "\\");
		String url = "src\\" + path + "\\"+interfaceName+".java";
		FileOutputStream fileWriter;
		try {
			fileWriter = new FileOutputStream(url);
			fileWriter.write(sb.toString().getBytes("UTF-8"));
			fileWriter.flush();
			fileWriter.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(url);
	}
}
